import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_widgets/config/kq_global.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_core_widget/widgets/image/kq_image.dart';

import '../../resources/images.dart';
import '../../resources/kq_theme_colors.dart';

///科强首页title
class KqAnimateTitle extends StatefulWidget {
  ///默认选中的index
  final int hoverIndex;

  ///首页title显示的数据
  final List<KqAnimateEntity> data;

  ///首页title点击的index
  final Function(int index)? onTap;

  ///首页title点击是否要弹出pop回调
  final Function(int index, BuildContext? context)? onTapPop;

  ///是否需要每次刷新时都执行动画
  final bool isNeedFlashEveryTime;

  ///动画执行时长
  final Duration duration;

  const KqAnimateTitle({
    super.key,
    required this.data,
    this.onTap,
    this.onTapPop,
    this.hoverIndex = 0,
    this.isNeedFlashEveryTime = false,
    this.duration = const Duration(milliseconds: 1400),
  });

  @override
  State<StatefulWidget> createState() => _KqAnimateTitleState();
}

class _KqAnimateTitleState extends State<KqAnimateTitle>
    with SingleTickerProviderStateMixin {
  ///偏移
  static double offset = 30.r;

  ///动画执行的总长度
  static double gap = 1000.0;

  ///当前选中的Title的index
  int _index = 0;

  late AnimationController controller;
  late Animation<double> animation;

  @override
  void initState() {
    super.initState();
    _index = widget.hoverIndex;

    controller = AnimationController(duration: widget.duration, vsync: this);
    animation = Tween(begin: 0.0, end: gap).animate(controller)
      ..addListener(() {
        if (mounted) {
          setState(() {});
        }
      });
    //启动动画(正向执行)
    controller.forward();
  }

  @override
  void didUpdateWidget(covariant KqAnimateTitle oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.isNeedFlashEveryTime) {
      _index = widget.hoverIndex;
    }
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 50.r,
      child: Stack(
        children: _getChildWidget(context),
      ),
    );
  }

  List<Widget> _getChildWidget(BuildContext context) {
    //背景
    List<Widget> listBg = [];
    //前景
    List<Widget> listFg = [];
    double width = context.width - offset;
    int length = widget.data.length;
    double part = length == 0 ? 0 : width / length;
    double animatePart = length == 0 ? 0 : gap / length;

    ///确定位置并调整顺序
    Widget? tempWidgetBg;
    for (int i = 0; i < length; i++) {
      ///范围0->1
      double mix =
          (animation.value - animatePart * (length - i - 1)) / animatePart;
      if (mix > 1) {
        mix = 1;
      }
      double left = -width * (1 - mix);
      double right = width * (1 - mix);
      Widget positionedBg = Positioned.fill(
        left: left,
        right: right,
        child: IgnorePointer(
          child: KqImage.assets(
            url: widget.data[i].url,
            fit: BoxFit.fitWidth,
            width: double.infinity,
            height: double.infinity,
            package: widget.data[i].package,
          ),
        ),
      );
      if (i == _index) {
        tempWidgetBg = Positioned.fill(
          left: left,
          right: right,
          child: IgnorePointer(
            child: KqImage.assets(
              url: widget.data[i].url2,
              fit: BoxFit.fitWidth,
              width: double.infinity,
              height: double.infinity,
              package: widget.data[i].package,
            ),
          ),
        );
      } else {
        if (i < _index) {
          listBg.add(positionedBg);
        } else {
          listBg.insert(0, positionedBg);
        }
      }
    }

    if (tempWidgetBg != null) {
      listBg.add(tempWidgetBg);
    }

    Widget? tempWidgetFg;
    for (int i = 0; i < length; i++) {
      ///范围-1->1
      double mix =
          (((animation.value - animatePart * (length - i - 1)) / animatePart) -
                  0.5) *
              2.0;
      if (mix > 1) {
        mix = 1;
      } else if (mix < -1) {
        mix = -1;
      }
      double left = (part * i + ((mix * part * (i + 1)) - part * (i + 1)) / 2);
      double right = (part * (length - i - 1) -
          ((mix * part * (i + 1)) - part * (i + 1)) / 2);

      ///Key
      GlobalKey key = GlobalKey();
      Widget positionedFg = Positioned(
        left: left,
        top: 6.r,
        bottom: 0,
        right: right,
        child: KqInkWell(
          key: key,
          onTap: () {
            if (_index == i && widget.data[i].isShowRightArrow) {
              widget.onTapPop?.call(_index, key.currentContext);
            } else {
              _index = i;
              widget.onTap?.call(_index);
              setState(() {});
            }
          },
          enableRipple: false,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                "${widget.data[i].title} ${widget.data[i].count}",
                style: TextStyle(
                  fontSize: 11.r,
                  color: KqThemeColors.textWhite,
                ),
              ),
              Visibility(
                visible: widget.data[i].isShowRightArrow,
                child: Container(
                  margin: EdgeInsets.only(left: 2.r),
                  child: SizedBox(
                    width: 8.r,
                    height: 8.r,
                    child: KqImage.assets(
                      url: Images.commonXiala,
                      fit: BoxFit.contain,
                      package: KqGlobal.packageName,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      );
      if (i == _index) {
        tempWidgetFg = positionedFg;
      } else {
        if (i < _index) {
          listFg.add(positionedFg);
        } else {
          listFg.insert(0, positionedFg);
        }
      }
    }

    if (tempWidgetFg != null) {
      listFg.add(tempWidgetFg);
    }

    listBg.addAll(listFg);
    return listBg;
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}

class KqAnimateEntity {
  ///标题
  final String title;

  ///数量
  final String count;

  ///是否显示右边三角，显示则有点击弹出pop事件回调
  final bool isShowRightArrow;

  /// 背景图片
  final String url;

  /// 选中后的图片
  final String url2;

  ///果是引用组件库的图片，必须得传
  final String? package;

  KqAnimateEntity({
    required this.title,
    required this.count,
    required this.url,
    required this.url2,
    this.isShowRightArrow = false,
    this.package,
  });
}
